<template>
  <div class="item-list">
    <div class="page-header">
      <h2>商品列表</h2>
      <!-- <el-button type="primary" @click="handleAdd">添加商品</el-button> -->
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="商品名称">
        <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="店铺">
        <el-select v-model="searchForm.shop_id" placeholder="请选择店铺" clearable filterable>
          <el-option v-for="shop in shops" :key="shop.id || shop.shop_id" :label="shop.shop_name || shop.name" :value="shop.id || shop.shop_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="searchForm.brand_id" placeholder="请选择品牌" clearable filterable>
          <el-option v-for="brand in brands" :key="brand.name" :label="brand.name" :value="brand.name" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="商品分类">
        <el-select v-model="searchForm.category_id" placeholder="请选择分类" clearable filterable>
          <el-option v-for="item in categories" :key="item.name" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item> -->
      
      <!-- 日期输入框 -->
      <el-form-item label="开始日期">
        <el-date-picker
          v-model="searchForm.start_date"
          type="date"
          start-placeholder="开始日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期">
        <el-date-picker
          v-model="searchForm.end_date"
          type="date"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品列表表格 -->
    <el-table
      v-loading="loading"
      :data="itemList"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="item_name" label="商品名称"></el-table-column>
      <el-table-column prop="item_price" label="商品价格" width="120">
        <template #default="{ row }">
          ¥{{ row.item_price }}
        </template>
      </el-table-column>
      <el-table-column prop="item_classification" label="分类"></el-table-column>
      <el-table-column prop="item_brand" label="品牌"></el-table-column>
      <el-table-column prop="cleaned_name" label="清洗后名称"></el-table-column>
      <el-table-column prop="created_at" label="创建时间"></el-table-column>
      <el-table-column prop="item_img" label="商品图片" width="120">
        <template #default="{ row }">
          <img :src="row.item_img" alt="商品图片" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column prop="base_unit" label="基础单位"></el-table-column>

      <el-table-column prop="base_price" label="基础价格" width="120">
        <template #default="{ row }">
          ¥{{ row.base_price }}
        </template>
      </el-table-column>

      <el-table-column prop="item_specs" label="规格" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sku_id" label="SKU编码"></el-table-column>

      <!-- 所属店铺 -->
      <el-table-column prop="shop_name" label="所属店铺" show-overflow-tooltip></el-table-column>
      <!-- <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            size="mini"
            @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="itemForm" :rules="rules" ref="itemForm" label-width="100px">
        <el-form-item label="商品名称" prop="item_name">
          <el-input v-model="itemForm.item_name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="item_classification">
          <el-input v-model="itemForm.item_classification"></el-input>
        </el-form-item>
        <el-form-item label="基础价格" prop="base_price">
          <el-input-number v-model="itemForm.base_price" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="商品价格" prop="item_price">
          <el-input-number v-model="itemForm.item_price" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="itemForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getItemList, createItem, updateItem, deleteItem } from '@/api/item'
import { getCategoryList } from '@/api/category'
import { getBrandList } from '@/api/config'
import { getShopList } from '@/api/shop'

export default {
  name: 'ItemList',
  data() {
    return {
      loading: false,
      itemList: [],
      // categories: [],
      brands: [],
      shops: [],
      searchForm: {
        name: '',
        category_id: '',
        brand_id: '',
        shop_id: ''
      },
      page: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      itemForm: {
        item_name: '',
        item_classification: '',
        base_price: 0,
        item_price: 0,
        item_specs: '',
        item_brand: '',
        shop_id: 1,  // 默认店铺ID
        shop_name: '',  // 店铺名称
        sku_id: '',  // SKU ID
        item_img: '',  // 商品图片
        run_id: ''  // 运行ID
      },
      rules: {
        item_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        item_classification: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ],
        base_price: [
          { required: true, message: '请输入基础价格', trigger: 'blur' }
        ],
        item_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
    // this.fetchCategories()
    this.fetchBrands()
    this.fetchShops()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.page,
          page_size: this.pageSize,
          ...this.searchForm
        }
        const response = await getItemList(params)
        console.log(">>>>>>>>>",response)
        if (response && response.items) {
          this.itemList = response.items
          this.total = response.total
        } else {
          this.itemList = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败，请稍后重试')
        this.itemList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    // async fetchCategories() {
    //   try {
    //     const response = await getCategoryList()
    //     if (Array.isArray(response)) {
    //       this.categories = response.map(item => ({ 
    //         id: item.id || item.category_id, 
    //         name: item.name || item.category_name 
    //       }))
    //     } else if (Array.isArray(response.items)) {
    //       this.categories = response.items.map(item => ({ 
    //         id: item.id || item.category_id, 
    //         name: item.name || item.category_name 
    //       }))
    //     } else {
    //       this.categories = []
    //     }
    //   } catch (error) {
    //     console.error('获取分类列表失败:', error)
    //     this.$message.error('获取分类列表失败')
    //   }
    // },
    async fetchBrands() {
      try {
        const response = await getBrandList()
        this.brands = response.items || response.data || []
      } catch (error) {
        console.error('获取品牌列表失败:', error)
        this.$message.error('获取品牌列表失败')
      }
    },
    async fetchShops() {
      try {
        // 添加 2 秒延迟
        await new Promise(resolve => setTimeout(resolve, 2000))
        const response = await getShopList({ page: 1, pageSize: 1000 })
        this.shops = response.items || response.data?.items || []
      } catch (error) {
        console.error('获取店铺列表失败:', error)
        this.$message.error('获取店铺列表失败')
      }
    },
    handleSearch() {
      this.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        name: '',
        category_id: '',
        brand_id: '',
        shop_id: ''
      }
      this.page = 1
      this.pageSize = 10
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '添加商品'
      this.itemForm = {
        item_name: '',
        item_classification: '',
        base_price: 0,
        item_price: 0,
        item_specs: '',
        item_brand: '',
        shop_id: 1,  // 默认店铺ID
        shop_name: '',  // 店铺名称
        sku_id: '',  // SKU ID
        item_img: '',  // 商品图片
        run_id: ''  // 运行ID
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      this.itemForm = { ...row }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该商品吗？', '提示', {
          type: 'warning'
        })
        await deleteItem(row.id)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
          console.error(error)
        }
      }
    },
    submitForm() {
      this.$refs.itemForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.itemForm.id) {
              await updateItem(this.itemForm.id, this.itemForm)
              this.$message.success('更新成功')
            } else {
              await createItem(this.itemForm)
              this.$message.success('创建成功')
            }
            this.dialogVisible = false
            this.fetchData()
          } catch (error) {
            this.$message.error(this.itemForm.id ? '更新失败' : '创建失败')
            console.error(error)
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.item-list {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 